package com.snake.springboot.authority.service.impl;

import com.snake.springboot.authority.api.model.VerifyTextCodeModel;
import com.snake.springboot.authority.api.service.VerifyTextCodeService;
import com.wf.captcha.GifCaptcha;
import com.wf.captcha.base.Captcha;
import org.snake.common.code.SerialNumberGeneratorFactory;
import org.snake.common.exception.ParameterException;
import org.snake.redis.commons.RedisPlusUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 类 {@code VerifyTextCodeServiceImpl}  <br> .
 * <p>文字验证码实现类
 * <p>创建时间：2025/04/17
 *
 * @author Huang.yj
 */
@Service
public class VerifyTextCodeServiceImpl implements VerifyTextCodeService {

    private String RedisKey = "orgBase:verifyTextCodeCache:%s";

    private RedisPlusUtils redisPlusUtils;

    @Autowired
    public VerifyTextCodeServiceImpl(RedisPlusUtils redisPlusUtils){
        this.redisPlusUtils = redisPlusUtils;
    }

    @Override
    public VerifyTextCodeModel createVerifyImage(){
        //ArithmeticCaptcha 数字加减乘除验证
        //ChineseCaptcha 中文验证
        //ChineseGifCaptcha 中文动态验证
        //GifCaptcha 动态字符验证
        //SpecCaptcha 字符验证
        //ArithmeticCaptcha captcha = new ArithmeticCaptcha(160,40,3);
        CustomGifCaptcha captcha = new CustomGifCaptcha(160,40,5);
        captcha.setCharType(Captcha.FONT_8);
        //生成验证码内容
        final String captchaText = captcha.text().toLowerCase();
        VerifyTextCodeModel model = new VerifyTextCodeModel();
        model.setUniqueId(SerialNumberGeneratorFactory.buildId4Bean());
        model.setImg(captcha.toBase64(""));
        //model.setVerifyCode(captchaText);
        String key = String.format(RedisKey,model.getUniqueId());
        redisPlusUtils.setOpsVal(key,captchaText,90);
        return model;
    }

    @Override
    public boolean checkVerifyCode(VerifyTextCodeModel model) {
        String key = String.format(RedisKey,model.getUniqueId());
        String verifyCode = redisPlusUtils.getOpsVal(key, String.class);
        model.getVerifyCode();
        if(verifyCode==null){
            throw new ParameterException("验证码过时或不存在，请重新获取");
        }
        else if(!verifyCode.equalsIgnoreCase(model.getVerifyCode())){
            throw new ParameterException("验证码不正确");
        }else{
            redisPlusUtils.delKey(key);
            return true;
        }
    }
}
